package com.iapplize.gcm.test;

import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager.LayoutParams;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

public class SendMessageDialog extends DialogFragment implements OnEditorActionListener , OnClickListener{

    private EditText mEditText;
    private Button send;
    private Button cancel;

    public SendMessageDialog() {
        // Empty constructor required for DialogFragment
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.send_message_fragment, container);
        mEditText = (EditText) view.findViewById(R.id.txt_your_name);
        send = (Button) view.findViewById(R.id.send);
        send.setOnClickListener(this);
        cancel = (Button) view.findViewById(R.id.cancel);
        cancel.setOnClickListener(this);
        
        getDialog().setTitle(getString(R.string.app_name));

        mEditText.requestFocus();
        getDialog().getWindow().setSoftInputMode(
                LayoutParams.SOFT_INPUT_STATE_VISIBLE);
        mEditText.setOnEditorActionListener(this);
        
        return view;
    }
    
    public interface SendMessageDialogListener {
        void onFinishEditDialog(String inputText);
    }

    
	public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (EditorInfo.IME_ACTION_DONE == actionId) {
        	
        	getDialog().getWindow().setSoftInputMode(
                    LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        	
            // Return input text to activity
        	SendMessageDialogListener activity = (SendMessageDialogListener) getActivity();
            activity.onFinishEditDialog(mEditText.getText().toString());
            this.dismiss();
            return true;
        }
        return false;
    }

	public void onClick(View v) {
		// TODO Auto-generated method stub
		getDialog().getWindow().setSoftInputMode(
                LayoutParams.SOFT_INPUT_STATE_HIDDEN);
		
		if(v == send){        	
            // Return input text to activity
        	SendMessageDialogListener activity = (SendMessageDialogListener) getActivity();
            activity.onFinishEditDialog(mEditText.getText().toString());
            this.dismiss();
		}else if(v == cancel){
			
			this.dismiss();
		}
	}
}